<template>
  <view class="container">
    <!-- 店铺信息 -->
    <view v-if="storeData.length > 0" class="store-info">
      <view class="store-left">
        <image :src="storeData[0].imgUrl" class="store-logo"></image>
      </view>
      <view class="store-right">
        <text class="store-name">{{ storeData[0].name }}</text>
        <br>
        <text class="store-sales">月售: {{ storeData[0].sales }} 起送: {{storeData[0].expressLimit }} &nbsp;&nbsp;基础运费: {{storeData[0].expressPrice }}</text>
        <br>
        <text class="store-coupon">VIP尊享满{{ storeData[0].couponThreshold }}元减{{ storeData[0].couponAmount }}元运费券</text>
      </view>
    </view>
    <!-- 侧边导航栏 -->
    <view class="sidebar-nav">
      <!-- 导航菜单项 -->
      <view 
        v-for="(item, index) in List" 
        :key="index" 
        class="nav-item" 
        :class="{active: activeIndex === index}"
        @click="NavClick(item, index)"
      >
        <text>{{ item.name }}</text>
      </view>
    </view>
    <!-- 内容区域 -->
    <view class="main-content">
      <!-- 商品列表 -->
      <view v-if="ProductList.length > 0" class="product-list">
        <view v-for="(i, pIndex) in ProductList" :key="pIndex" class="product-item" @click="showProductInModal(i)">
          <view class="product-left">
            <image :src="i.imgUrl" class="product-img"></image>
          </view>
          <view class="product-right">
            <text class="product-name">{{ i.name }} {{ i.specification }}</text>
            <br>
            <text class="product-sales">月售 {{ i.sales}} 件</text>
            <br>
            <text class="price-old">¥{{ i.olderPrice }}</text>
            <text class="price-new">¥{{ i.price }}</text>
            <view class="quantity-control">
              <button class="round-btn" @click="decreaseQuantity(i)">-</button>
              <span>{{ i.quantity || 0 }}</span>
              <button class="round-btn" @click="increaseQuantity(i)">+</button>
            </view>
          </view>
        </view>
      </view>
      <view v-else-if="loadingProductList" class="loading">加载中...</view>
    </view>
     <!-- 底部购物车栏 -->
    <view class="cart-bar">
      <view class="cart-icon" @click.stop="toggleCartModal">
        <image src="@/static/basket.png" mode="aspectFit"></image>
        <text class="cart-num">{{ totalCartQuantity }}</text>
      </view>
      <text class="cart-total">总计: ¥ {{ totalPrice }}</text>
      <button class="carts" @click="goToCartPage">去结算</button>
    </view>

    <!-- 底部弹框 -->
    <view v-if="showCartModal" class="bottom-modal" @click.stop>
      <view class="modal-header">
        <view class="header-left">
          <view class="select-all">
            <text class="modal-title">购物车商品</text>
          </view>
        </view>
        <view class="header-right">
          <text class="clear-cart" @click="confirmClearCart">清除</text>
        </view>
      </view>
      <view class="modal-content">
        <view v-for="(product, index) in selectedProducts" :key="index" class="product-item">
          <view class="product-left">
            <image :src="product.imgUrl" class="product-img"></image>
          </view>
          <view class="product-info">
            <text class="product-name">{{ product.name }} {{ product.specification }}</text>
            <br>
            <view class="quantity-control">
              <button class="round-btn" @click.stop="decreaseQuantity(product)">-</button>
              <span>{{ product.quantity }}</span>
              <button class="round-btn" @click.stop="increaseQuantity(product)">+</button>
            </view>
            <text class="price-new">单价: ¥{{ product.price }}</text>
          </view>
          <view class="product-delete" @click.stop="removeProduct(product)">
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      storeData: [],
      List: [
        {
          name: "全部商品",
          type: "all",
          data: []
        },
        {
          name: "秒杀",
          type: "kill",
          data: []
        },
        {
          name: "新鲜水果",
          type: "fruit",
          data: []
        }
      ],
      ProductList: [],
      loadingStoreData: false,
      loadingProductList: false,
      totalCartQuantity: 0,
      totalPrice: 0,
      showCartModal: false,
      selectedProducts: [],
      activeIndex: 0
    };
  },
  onLoad: function (options) {
    const Id = options.id;
    this.loadingStoreData = true;
    uni.request({
      url: `http://localhost:3000/data?id=${Id}`,
      method: 'GET',
      success: (res) => {
        this.storeData = res.data;
        this.loadingStoreData = false;
        
        // 加载商品前先清除其他商店的购物车数据
        this.clearOtherShopCartItems(this.storeData[0].id);
        
        this.querydata(this.List[0].type);
      },
      fail: (err) => {
        console.error('请求失败', err);
        this.loadingStoreData = false;
      }
    });
  },
  methods: {
    // 新增方法：清除其他商店的购物车商品
    clearOtherShopCartItems(currentShopId) {
      let cartItems = uni.getStorageSync('cartItems') || [];
      cartItems = cartItems.filter(item => item.shopId === currentShopId);
      uni.setStorageSync('cartItems', cartItems);
    },
    NavClick(item, index) {
      this.activeIndex = index;
      if (item.data.length === 0) {
        this.querydata(item.type);
      } else {
        this.ProductList = item.data;
      }
    },
    querydata(type) {
      if (!this.storeData) {
        console.warn('storeData 未获取到');
        return;
      }
      this.loadingProductList = true;
      uni.request({
        url: `http://localhost:3000/${type}?shopId=${this.storeData[0].id}`, 
        method: 'GET',
        success: (res) => {
          const targetItem = this.List.find(i => i.type === type);
          if (targetItem) {
            // 从本地存储获取购物车数据，只获取当前商店的
            const cartItems = uni.getStorageSync('cartItems') || [];
            const currentShopCartItems = cartItems.filter(item => item.shopId === this.storeData[0].id);
            
            // 合并商品数据和购物车数据
            targetItem.data = res.data.map(item => {
              const cartItem = currentShopCartItems.find(ci => ci._id === item._id);
              return {
                ...item,
                quantity: cartItem ? cartItem.quantity : 0
              };
            });
            
            this.ProductList = targetItem.data;
            this.loadingProductList = false;
            
            this.updateTotalCartQuantity();
            this.calculateTotalPrice();
          }
        },
        fail: (err) => {
          console.error('请求数据失败:', err);
          this.loadingProductList = false;
        }
      });
    },
    increaseQuantity(product) {
      if (!product.quantity) {
        product.quantity = 1;
      } else {
        product.quantity++;
      }
      this.updateTotalCartQuantity();
      this.calculateTotalPrice();
      
      let cartItems = uni.getStorageSync('cartItems') || [];
      // 先移除其他商店的商品
      cartItems = cartItems.filter(item => item.shopId === this.storeData[0].id);
      
      const existingItemIndex = cartItems.findIndex(item => item._id === product._id);
      if (existingItemIndex > -1) {
        cartItems[existingItemIndex].quantity = product.quantity;
      } else {
        cartItems.push({
          _id: product._id,
          name: product.name,
          specification: product.specification,
          imgUrl: product.imgUrl,
          sales: product.sales,
          price: product.price,
          quantity: product.quantity,
          shopId: this.storeData[0].id,
          shopName: this.storeData[0].name
        });
      }
      uni.setStorageSync('cartItems', cartItems);
    },
    decreaseQuantity(product) {
      if (product.quantity && product.quantity > 0) {
        product.quantity--;
      }
      this.updateTotalCartQuantity();
      this.calculateTotalPrice();
      
      let cartItems = uni.getStorageSync('cartItems') || [];
      // 先移除其他商店的商品
      cartItems = cartItems.filter(item => item.shopId === this.storeData[0].id);
      
      const existingItemIndex = cartItems.findIndex(item => item._id === product._id);
      if (existingItemIndex > -1) {
        if (product.quantity === 0) {
          cartItems.splice(existingItemIndex, 1);
        } else {
          cartItems[existingItemIndex].quantity = product.quantity;
        }
      }
      uni.setStorageSync('cartItems', cartItems);
    },
    updateTotalCartQuantity() {
      this.totalCartQuantity = this.ProductList.reduce((total, product) => {
        return total + (product.quantity || 0);
      }, 0);
    },
    calculateTotalPrice() {
      this.totalPrice = this.ProductList.reduce((total, product) => {
        return total + (product.quantity || 0) * product.price;
      }, 0).toFixed(2);
    },
     goToCartPage() {
  const cartItems = uni.getStorageSync('cartItems') || [];
  const currentShopItems = cartItems.filter(item => item.shopId === this.storeData[0].id);
  
  if (currentShopItems.length > 0) {
    try {
      const productsStr = JSON.stringify(currentShopItems);
      uni.navigateTo({
        url: `/pages/detail/gotoCartpage?products=${productsStr}`
      });
    } catch (error) {
      console.error('JSON.stringify error:', error);
      uni.showToast({
        title: '数据处理出错，请稍后重试',
        icon: 'none'
      });
    }
  } else {
    uni.showToast({
      title: '购物车为空',
      icon: 'none'
    });
  }
},
    toggleCartModal() {
      if (this.totalCartQuantity > 0) {
        this.showCartModal = !this.showCartModal;
        if (this.showCartModal) {
          this.selectedProducts = this.ProductList.filter(product => product.quantity > 0);
        }
      } else {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
      }
    },
    showProductInModal(product) {
      if (product.quantity > 0) {
        this.showCartModal = true;
        const existingIndex = this.selectedProducts.findIndex(p => p._id === product._id);
        if (existingIndex > -1) {
          this.selectedProducts[existingIndex] = product;
        } else {
          this.selectedProducts.push(product);
        }
      } else {
        uni.showToast({
          title: '商品数量不足',
          icon: 'none'
        });
      }
    },
    removeProduct(product) {
      // 提升弹框的z-index
      const modalOptions = {
        title: '提示',
        content: '确定要删除该商品吗？',
        zIndex: 1200, // 设置一个比其他元素更高的z-index值
        success: (res) => {
          if (res.confirm) {
            const index = this.selectedProducts.findIndex(p => p._id === product._id);
            if (index !== -1) {
              this.selectedProducts.splice(index, 1);
            }
            
            const productIndex = this.ProductList.findIndex(p => p._id === product._id);
            if (productIndex !== -1) {
              this.$set(this.ProductList[productIndex], 'quantity', 0);
            }
            
            this.updateCartStorage();
            this.updateTotalCartQuantity();
            this.calculateTotalPrice();
          }
        }
      };
      uni.showModal(modalOptions);
    },
    confirmClearCart() {
      // 提升弹框的z-index
      const modalOptions = {
        title: '提示',
        content: '确定要清空购物车吗？',
        zIndex: 1200, // 设置一个比其他元素更高的z-index值
        success: (res) => {
          if (res.confirm) {
            this.selectedProducts.forEach(product => {
              const index = this.ProductList.findIndex(p => p._id === product._id);
              if (index !== -1) {
                this.$set(this.ProductList[index], 'quantity', 0);
              }
            });
            
            this.selectedProducts = [];
            this.updateCartStorage();
            this.updateTotalCartQuantity();
            this.calculateTotalPrice();
          }
        }
      };
      uni.showModal(modalOptions);
    },
    updateCartStorage() {
      // 只存储当前商店的商品
      const cartItems = uni.getStorageSync('cartItems') || [];
      const otherShopItems = cartItems.filter(item => item.shopId !== this.storeData[0].id);
      
      const currentShopItems = this.ProductList
        .filter(item => item.quantity > 0)
        .map(item => ({
          _id: item._id,
          name: item.name,
          specification: item.specification,
          imgUrl: item.imgUrl,
          sales: item.sales,
          price: item.price,
          quantity: item.quantity,
          shopId: this.storeData[0].id,
          shopName: this.storeData[0].name
        }));
      
      // 合并其他商店的商品和当前商店的商品
      uni.setStorageSync('cartItems', [...otherShopItems, ...currentShopItems]);
    },
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.store-info {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  margin-top: 40px;
}

.store-left {
  margin-right: 10px;
}

.store-logo {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.store-name {
  font-size: 16px;
  font-weight: bold;
}

.store-sales, .store-coupon {
  font-size: 12px;
  color: #666;
}

.sidebar-nav {
  width: 120px;
  background-color: #f9f9f9;
  padding: 15px 0;
  display: flex;
  flex-direction: column;
  margin-top: 70px;
}

.store-coupon{
  color: rgb(235, 60, 60);
  font-size: 16px;
}

.nav-item {
  padding: 12px 15px;
  cursor: pointer;
  text-align: center;
  transition: background-color 0.3s;
}

.nav-item.active {
  background-color: #fff;
  color: #FF5722;
  font-weight: bold;
  border-left: 3px solid #FF5722;
}

.nav-item:hover {
  background-color: #e0e0e0;
}

.main-content {
  flex: 1;
  padding: 15px;
  margin-left: 120px;
  margin-top: -160px;
  padding-bottom: 70px;
}

.product-list {
  overflow-y: auto;
  background-color: #fff;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eaeaea;
}

.product-left {
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.product-img {
  width: 80px;
  height: 80px;
}

.product-right {
  flex: 1;
}

.product-name {
  font-size: 14px;
  font-weight: normal;
  margin-bottom: 5px;
}

.product-sales {
  font-size: 12px;
  color: #666;
}

.price-old {
  color: #999;
  text-decoration: line-through;
  margin-right: 5px;
}

.price-new {
  color: #FF5722;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 0; 
  justify-content: center;
  margin-left: 150px;
}

.round-btn {
  background-color: transparent; 
  border: none; 
  outline: none;
  font-size: 12px;
  color: #FF5722; 
  padding: 0; 
  margin: 0 3px;
  line-height: 1;
  min-width: auto;
  min-height: auto;
}

.round-btn::after {
  border: none;
}

.cart-bar {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #eaeaea;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.cart-icon {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.cart-icon image {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

.cart-num {
  font-size: 12px;
  background-color: #FF5722;
  color: white;
  border-radius: 50%;
  padding: 2px 5px;
}

.cart-total {
  font-size: 14px;
  flex: 1;
  text-align: right;
}

.carts{
  background-color: #007AFF;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 3px;
}

.bottom-modal {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.16), 0 -3px 6px rgba(0, 0, 0, 0.23);
  z-index: 1100;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
}

.select-all {
  display: flex;
  align-items: center;
}

.modal-title {
  font-size: 16px;
  font-weight: bold;
  margin-left: 5px;
}

.header-right {
  display: flex;
  align-items: center;
  /* margin-top: 150px; */
  /* z-index:2000; */
}

.clear-cart {
  color: #999;
  font-size: 14px;
  margin-right: 15px;
  /* z-index:2000; */
}

.modal-content {
  max-height: 50vh;
  overflow-y: auto;
}

.product-delete {
  color: #ff5722;
  padding: 5px 10px;
}

.bottom-modal {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.16), 0 -3px 6px rgba(0, 0, 0, 0.23);
  z-index: 1100;
  pointer-events: auto;
}

.product-item {
  padding: 15px;
}
</style>